//
//  KRSearchGetListController.m
//  cookBook
//
//  Created by kuroken on 16/1/26.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRSearchGetListController.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import <SVProgressHUD.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRSearchGetResult.h"
#import "KRSearchGetListAlbumCell.h"
#import "KRSearchGetListRecipeCell.h"
#import "KRSearchNoDataCell.h"
#import "KRNoNetCell.h"
#import "KRSearchGetResultAlbum.h"
#import "KRSearchGetResultList.h"
#import "KRAlbumInfoController.h"
#import "KRRecipeInfoController.h"
#import "KRHomeDataTool.h"

static NSUInteger const limit = 20;

@interface KRSearchGetListController ()

/** KRSearchGetResult 模型 */
@property (nonatomic, strong) KRSearchGetResult *result;

@property (nonatomic, assign) NSUInteger offset;

@property (nonatomic, assign, getter=isError) BOOL error;

/** 当前请求 */
@property (nonatomic, strong) NSURLSessionDataTask *currentDataTask;

@property (nonatomic, weak) UIView *footerView;

@end

@implementation KRSearchGetListController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    self.tableView.backgroundColor = [UIColor redColor];
    
    //  设置分隔线的位置和尺寸
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 110, 0, 0);

    // 去除多余的分隔线
    self.tableView.tableFooterView = [[UIView alloc] init];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self scrollViewDidScroll:self.tableView];
    if (_footerView) {
        [self.tableView.mj_footer setHidden:NO];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.currentDataTask cancel];
    self.currentDataTask = nil;
    [SVProgressHUD dismiss];
    [self.tableView.mj_footer setHidden:YES];
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

- (void)setKeyword:(NSString *)keyword
{
    _keyword = keyword;
    
    if (!keyword) { // 点击了搜索按钮
        self.result = nil;
        self.error = NO;
        [self.tableView reloadData];
        return;
    }
    
    // 将搜索关键字keyword存入数据库
    [KRHomeDataTool saveSearchWord:keyword];

    [self loadData];
}

- (void)loadMoreData
{
    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRSearchGetList;
        requestParams[@"keyword"] = self.keyword;
        requestParams[@"limit"] = [NSString stringWithFormat:@"%d", (int)limit];
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];

    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        KRSearchGetResult *result = [KRSearchGetResult mj_objectWithKeyValues:json[@"result"]];
        NSArray *listArray = result.list;
        [self.result.list addObjectsFromArray:listArray];
        
        self.offset += listArray.count;
        
        if (self.offset >= [self.result.count integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [self.tableView reloadData];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (self.currentDataTask != task) return;

        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        KRLog(@"%@, %@", self, error);
    }];
}

/**
 *  上拉刷新控件
 */
- (void)setupFooterRefresh
{
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
    self.footerView = footer;
}

- (void)loadData
{
    self.offset = 0;
    [SVProgressHUD show];
    self.tableView.userInteractionEnabled = NO;
    self.tableView.scrollEnabled = NO;

    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRSearchGetList;
        requestParams[@"keyword"] = self.keyword;
        requestParams[@"limit"] = [NSString stringWithFormat:@"%d", (int)limit];
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];

    } success:^(NSURLSessionDataTask *task, id json) {
#warning 此时返回的数据是否与当前搜索框内容一致!
        if (task != self.currentDataTask) return;

        // 上拉刷新控件
        [self setupFooterRefresh];

        self.error = NO;
        self.tableView.scrollEnabled = YES;

        self.result = [KRSearchGetResult mj_objectWithKeyValues:json[@"result"]];

        self.offset += self.result.list.count;
        
        [self.tableView reloadData];
        
        if (self.offset >= [self.result.count integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (task != self.currentDataTask) return;
        
        self.error = YES;
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
        [self.tableView.mj_footer removeFromSuperview];
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([self.delegate respondsToSelector:@selector(searchGetListControllerDidStartScroll)]) {
        [self.delegate searchGetListControllerDidStartScroll];
    }
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    if (!self.result) return 0;
    
    if (self.result.album && self.result.list.count) { // 有专辑且有列表
        return 2;
    } else if (self.result.album || self.result.list.count) { // 有专辑或有列表
        return 1;
    } else if (!self.result.album && !self.result.list.count) {
        return 1;
    } else {
        return 0;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1;
    if (self.result.album && section == 0) {
        return 1;
    } else if (self.result.list.count) {
        return self.result.list.count;
    } else if (!self.result.album && !self.result.list.count) {
        return 1;
    } else {
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"网速不给力,无法加载"];
        return cell;
    }
    
    if (self.result.album && indexPath.section == 0) { // 专辑
        KRSearchGetListAlbumCell *cell = [KRSearchGetListAlbumCell cellWithTableView:tableView];
        cell.album = self.result.album;
        return cell;
    } else if (self.result.list.count){ // list
        KRSearchGetListRecipeCell *cell =[KRSearchGetListRecipeCell cellWithTableView:tableView];
        cell.recipe = self.result.list[indexPath.row];
        return cell;
    } else { // 没有数据
        return [KRSearchNoDataCell cellWithTableView:tableView];
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.result.album && indexPath.section == 0) { // 专辑
        return 115;
    } else if (self.result.list.count){ // list
        return 85;
    } else { // 没有数据或请求失败
        return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
    
    if (self.result.album && indexPath.section == 0) { // 专辑
        KRAlbumInfoController *infoVc = [[KRAlbumInfoController alloc] init];
        infoVc.albumID = self.result.album.albumID;
        [self.navigationController pushViewController:infoVc animated:YES];

    } else if (self.result.list.count){ // list
        KRRecipeInfoController *infoVc = [[KRRecipeInfoController alloc] init];
        infoVc.recipeID = self.result.list[indexPath.row].list_recipeID;
        [self.navigationController pushViewController:infoVc animated:YES];
    }
}

@end